package com.example.adminvue.filter;

import com.alibaba.fastjson.JSON;
import com.example.adminvue.domain.LoginUser;
import com.example.adminvue.domain.TokenUser;
import com.example.adminvue.domain.User;
import com.example.adminvue.utils.JwtUtil;
import com.example.adminvue.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * token 验证过滤器
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("Authorization");
        if(token!=null && token.startsWith("Bearer ")){
            token = token.replace("Bearer ", "");
        }
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析token
        String subject;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            subject = claims.getSubject();

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token过期或异常");
        }
        TokenUser tokenUser = JSON.parseObject(subject,TokenUser.class);
        //从redis中获取用户信息
        String redisKey = "login:" + tokenUser.getUserId();
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录");
        }
        //存入securityContextHolder中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());//这里必须调用三个参数的构造，才可以设置已授权
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //每次请求成功，重新发送jwt token.使token刷新
        User user=new User();
        user.setUserId(loginUser.getUser().getUserId());
        user.setNickName(loginUser.getUser().getNickName());
        user.setEmail(loginUser.getUser().getEmail());
        user.setPhonenumber(loginUser.getUser().getPhonenumber());
        user.setSex(loginUser.getUser().getSex());
        String token_str = JwtUtil.makeTokenMap(user);
        String jwt = JwtUtil.createJWT(token_str);
        response.addHeader("token", jwt);
        //放行
        filterChain.doFilter(request, response);
    }
}
